package com.gzu.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.constant.AddressStatusConstant;
import com.gzu.shop.constant.JwtClaimsConstant;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.context.BaseContext;
import com.gzu.shop.entity.Address;
import com.gzu.shop.entity.Order;
import com.gzu.shop.exception.AddressBookBusinessException;
import com.gzu.shop.exception.OrderBusinessException;
import com.gzu.shop.mapper.AddressMapper;
import com.gzu.shop.mapper.ProvinceMapper;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Clown
 */
@Slf4j
@RestController
@RequestMapping("/address")
@AllArgsConstructor
@Tag(name = "用户地址管理相关接口")
public class AddressController extends BaseController<AddressService, Address> {
    private AddressMapper addressMapper;
    private ProvinceMapper provinceMapper;

    @Override
    @Operation(summary = "重写父类方法，实现添加功能，填充部分字段")
    @PostMapping("/add")
    public Result<Void> addEntity(@RequestBody Address entity) {

        // 获取用户Id
        Integer userId = getUserId(entity);
        // 设置用户Id
        entity.setUserId(String.valueOf(userId));

        // 查询是否已经有默认地址了
        // 已经存在默认地址并且当前地址也是默认地址
        if (addressMapper.exists(new QueryWrapper<Address>().eq("is_default", AddressStatusConstant.YES)
                .eq("user_id", userId))
                && Objects.equals(entity.getIsDefault(), AddressStatusConstant.YES)) {
            throw new AddressBookBusinessException(MessageConstant.DEFAULT_ADDRESS_EXISTED);
        }

        // 填充创建时间
        entity.setCreateTime(String.valueOf(System.currentTimeMillis()));
        // 填充更新时间
        entity.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        return super.addEntity(entity);
    }

    @GetMapping("/getDefault")
    @Operation(summary = "获取默认地址")
    public Result<Address> getById() {
        // 获取userId
        // 获取用户ID
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
        // 判断是否有默认地址，如果有就找到地址
        QueryWrapper<Address> queryWrapper = new QueryWrapper<Address>().eq("user_id", userId).
                eq("is_default", AddressStatusConstant.YES);

        // 获取地址
        Address address = addressMapper.selectOne(queryWrapper);

        if (Objects.isNull(address)) {
            return Result.success(ResultStatus.SUCCESS, null);
        }

        // 填充省份字段
        if (!address.getProvinceId().isEmpty()) {
            address.setProvinceName(provinceMapper.selectById(address.getProvinceId()).getName());
        }

//        log.info("address: {}", address);


        return Result.success(ResultStatus.SUCCESS, address);
    }

    @Override
    @Operation(summary = "实现通过id删除功能")
    @DeleteMapping("/del/{id}")
    public Result<Void> deleteById(@PathVariable Long id) {
        return super.deleteById(id);
    }

    @Override
    @Operation(summary = "实现批量删除功能")
    @DeleteMapping("/deleteBatch")
    public Result<Void> deleteBatch(@RequestBody List<Long> ids) {
        return super.deleteBatch(ids);
    }

    @Override
    @Operation(summary = "重写父类方法，实现编辑实体功能")
    @PostMapping("/edit")
    public Result<Void> editById(@RequestBody Address entity) {
        // 获取用户ID
        Integer userId = getUserId(entity);

        // 查询是否已经有默认地址了
        // 已经存在默认地址并且当前地址也是默认地址
        if (addressMapper.exists(new QueryWrapper<Address>().eq("is_default", AddressStatusConstant.YES)
                .eq("user_id", userId))
                && Objects.equals(entity.getIsDefault(), AddressStatusConstant.YES)) {
            throw new AddressBookBusinessException(MessageConstant.DEFAULT_ADDRESS_EXISTED);
        }
        // 设置更新时间
        entity.setUpdateTime(String.valueOf(System.currentTimeMillis()));

        return super.editById(entity);
    }

    @Override
    @Operation(summary = "重载父类方法，填充非数据字段省份名")
    @PostMapping("/page/{startPage}/{pageSize}")
    public Result<IPage<Address>> page(@PathVariable int startPage,
                                       @PathVariable int pageSize,
                                       @RequestBody(required = false) SearchCondition<Address> searchCondition) {

        // 获取userId
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
        searchCondition.getSearch().setUserId(String.valueOf(userId));

        Result<IPage<Address>> page = super.page(startPage, pageSize, searchCondition);
        List<Address> records = page.getData().getRecords();

        // 重新给地址添加上省份字段
        for (Address address : records) {
            if (address.getProvinceId() != null && !address.getProvinceId().isEmpty()) {
                address.setProvinceName(provinceMapper.selectById(address.getProvinceId()).getName());
            }
        }
        page.getData().setRecords(records);
        return page;
    }

    // 判断关键字段是否为空，为空则抛出异常，获取userId
    private static Integer getUserId(Address entity) {
        // 如果添加数据为空
        if (entity == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_DETAIL_EMPTY);
        }

        // 如果收货人姓名为空
        if (entity.getName() == null || entity.getName().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_RECEIVER_NAME_EMPTY);
        }
        // 如果收货电话号码为空
        if (entity.getMobile() == null || entity.getMobile().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_RECEIVER_NAME_EMPTY);
        }
        // 如果收货地址为空
        if (entity.getDescription() == null || entity.getDescription().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_DETAIL_EMPTY);
        }
//        // 如果收货省份为空
//        if (entity.getProvinceId() == null || entity.getProvinceId().isEmpty()) {
//            throw new AddressBookBusinessException(MessageConstant.ADDRESS_PROVINCE_EMPTY);
//        }

        // 获取userId
        // 获取用户ID
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        return (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
    }
}
